const {ListNode, LinkedList} = require('./1. 建立线性链表')
// 1. 链表表头插入元素
function insertFront(linkedList, val) {
    let node = new ListNode(val)
    node.next = linkedList.head
    linkedList.head = node
}

let linkedList = new LinkedList([2, 3, 5, 6, 8, 1])
insertFront(linkedList, 99)
console.log(linkedList)

// 2. 链表尾部插入元素
function insertRear(linkedList, val) {
    let node = new ListNode(val)
    let cur = linkedList.head
    while (cur.next) {
        cur = cur.next
    }
    cur.next = node
}
let linkedList2 = new LinkedList([2, 3, 5, 6, 8, 1])
insertRear(linkedList2, 99)
console.log(linkedList2)

// 3. 链表中间插入元素
function insertInside(linkedList, index, val) {
    let count = 0
    let cur = linkedList.head
    while (cur && count < index - 1) {
        count += 1
        cur = cur.next
    }
    if (!cur) {
        return 'Error'
    }
    let node = new ListNode(val)
    node.next = cur.next
    cur.next = node
}
let linkedList3 = new LinkedList([2, 3, 5, 6, 8, 1])
insertInside(linkedList3, 2, 99)
console.log(linkedList3);
